<template>
  <div>
    <el-form ref="form" v-loading="loading" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('上级目录')" prop="parentId">
            <treeselect v-model="form.parentId" :options="keyWordOptions" :show-count="true" :normalizer="normalizer" :placeholder="$t('请选择')">
              <label slot="option-label" slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }" :class="labelClassName">
                {{ $t(node.label) }}
                <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
              </label>
            </treeselect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('类型')" prop="type">
            <el-radio-group v-model="form.type" :disabled="form.id !== undefined && form.id !== null && form.id !== ''">
              <el-radio-button
                v-for="dict in typeFolderOrKeyWOrdOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
                @change="typeChangeToSingleMultiple(form.type)"
              >{{ $t(dict.dictLabel) }}</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('名称')" prop="keyWord">
            <el-input v-model="form.keyWord" :placeholder="$t('名称')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col v-if="isHidden && form.type !== 'key_word_tree'" :span="12">
          <el-form-item :label="$t('唯一标识')" prop="code">
            <span slot="label">
              {{ $t('唯一标识') }}
              <el-tooltip placement="top">
                <div slot="content">
                  <span v-html="$t('只包含字母、数字和下划线<br/>使用下划线分隔，前缀使用v、f、p<br/>不要使用MySQL的保留字作为名称<br/>例子：视图(v_deal_info)，函数(f_get_userName)，过程(p_fundEntity_investorEntity_batch_contributionNotice)')" />
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-input v-model="form.code" :disabled="(isBuiltin || form.id) && codeDisabled" :placeholder="$t('标识')" />
          </el-form-item>
        </el-col>
        <el-col v-if="isHidden && form.type !== 'key_word_tree'" :span="12">
          <el-form-item :label="$t('唯一标识别名')" prop="codeFlag">
            <span slot="label">
              {{ $t('唯一标识别名') }}
              <el-tooltip placement="top">
                <div slot="content">
                  <span v-html="$t('撰写报告中关键字的开头')" />
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-input v-model="form.codeFlag" :disabled="isBuiltin && codeFlagDisabled" :placeholder="$t('标识')" />
          </el-form-item>
        </el-col>
        <!-- <el-col v-if="isHidden && form.type !== 'key_word_tree'" :span="12">
          <el-form-item :label="$t('文本类型')" prop="singleMultiple">
            <el-select v-model="form.singleMultiple" :placeholder="$t('请选择')">
              <el-option
                v-for="dict in singleMultipleOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col> -->
        <!-- <el-col v-if="isHidden && form.type !== 'key_word_tree'" :span="12">
          <el-form-item :label="$t('是否内置数据')" prop="isBuiltinData">
            <dictSelect
              v-model="form.isBuiltinData"
              :clearable="true"
              dictionary="sys_yes_no"
              :disabled="isBuiltin"
            />
          </el-form-item>
        </el-col> -->
        <el-col v-if="isHidden && form.type !== 'key_word_tree'" :span="12">
          <el-form-item :label="$t('数据源')" prop="dataSourceId">
            <el-select v-model="form.dataSourceId" clearable :placeholder="$t('数据源')" @change="checkScriptBySql">
              <el-option
                v-for="(item, index) in dataSourceOptions"
                :key="index"
                :label="item.dataSourceName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="isHidden && form.type !== 'key_word_tree'" :span="12">
          <el-form-item :label="$t('使用范围')" prop="usageScope">
            <dictSelect
              v-model="form.usageScope"
              :clearable="true"
              :multiple="true"
              dictionary="usage_scope"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="isHidden && form.type !== 'key_word_tree'" :span="12">
          <el-form-item :label="$t('数据类型')" prop="dataType">
            <dictSelect
              v-model="form.dataType"
              :clearable="true"
              dictionary="key_data_type"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="isHidden && form.type !== 'key_word_tree'" :span="12">
          <el-form-item :label="$t('模板关键字类型')" prop="templateType">
            <el-select v-model="form.templateType" placeholder="请选择" clearable>
              <el-option
                v-for="item in templateTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="form.type === 'image'" :span="12">
          <el-form-item :label="$t('图表类型')" prop="imgType">
            <el-select v-model="form.imgType" :placeholder="$t('请选择')" @change="checkScriptBySql">
              <el-option
                v-for="dict in chartTypeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="isHidden && form.type !== 'key_word_tree'" :span="12">
          <el-form-item :label="$t('引用物理表情况')" prop="quoteTableNum">
            <div style="margin-left: 5px;">
              <span v-if="form.quoteTableNum !== 0" class="link-type" @click="viewQuoteTableList(form)">{{ form.quoteTableNum }}</span>
              <span v-else>0</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col v-if="isHidden && form.type !== 'key_word_tree'" :span="12">
          <el-form-item :label="$t('引用数据情况')" prop="quoteNum">
            <div style="margin-left: 5px;">
              <!-- {{ form.quoteNum }} -->
              <span v-if="form.quoteNum !== 0" class="link-type" @click="viewQuoteList(form, 'quote')">{{ form.quoteNum }}</span>
              <span v-else>0</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col v-if="isHidden && form.type !== 'key_word_tree'" :span="12">
          <el-form-item :label="$t('被引用数据情况')" prop="quotedNum">
            <div style="margin-left: 5px;">
              <!-- {{ form.quotedNum }} -->
              <span v-if="form.quotedNum !== 0" class="link-type" @click="viewQuoteList(form, 'quoted')">{{ form.quotedNum }}</span>
              <span v-else>0</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col v-if="isHidden && form.type !== 'key_word_tree'" :span="24">
          <el-form-item :label="$t('取值逻辑说明')" prop="valueNotes">
            <el-input v-model="form.valueNotes" type="textarea" :placeholder="$t('取值逻辑说明')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
        <!-- v-if="isHidden" -->
        <el-col v-if="form.type !== 'folder'" :span="24">
          <el-form-item>
            <span slot="label">
              {{ $t('Sql脚本') }}
              <span style="color: rgb(179, 172, 172);font-weight: normal;font-size: 13px;">
                <span>示例: select </span>
                <span style="color: red;">ifnull(</span>
                <span>a.act_title</span>
                <span style="color: red;">, '') as</span>
                <span>'标题'</span>
                <span v-show="form.type === 'key_word_tree'">, </span>
                <span v-show="form.type === 'key_word_tree'" style="color: red;">ifnull(</span>
                <span v-show="form.type === 'key_word_tree'">a.amount_money</span>
                <span v-show="form.type === 'key_word_tree'" style="color: red;">, 0) as</span>
                <span v-show="form.type === 'key_word_tree'">'金额'</span>
                <span> from oa_expense a where a.id = </span>
                <span style="color: red;">${id}</span>
              </span>
            </span>
            <el-input v-show="isBuiltin" v-model="form.sqlScript" type="textarea" :disabled="true" />
            <div v-show="!isBuiltin">
              <codemirror ref="sqlScript" v-model="form.sqlScript" :options="cmOptions" class="codesql" />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <div v-if="form.type !== 'folder'">
        <div class="area-header">
          <span v-if="filedShow" class="area-header-title" style="float: left;">{{ $t('字段列表') }}</span>
          <span style="float: right;font-size: 14px;">
            <template>
              <el-button
                v-hasPermi="['system:word:edit']"
                type="primary"
                size="mini"
                @click="previewScriptBySql"
              >{{ $t('预览数据') }}</el-button>
            </template>
          </span>
          <span style="float: right;font-size: 14px;margin-right: 10px;">
            <template>
              <el-button
                v-hasPermi="['system:word:edit']"
                type="primary"
                size="mini"
                @click="checkScriptBySql"
              >{{ $t('测试') }}</el-button>
            </template>
          </span>
        </div>
        <el-table
          v-if="filedShow"
          :data="form.fieldList"
          border
          class="nowrapTable formTable"
        >
          <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('字段类型')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('字段类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'fieldList.' + scope.$index + '.type'" :rules="fieldListRules.type">
                <el-select
                  v-model="scope.row.type"
                  clearable
                  :placeholder="$t('请选择')"
                  style="width: 100%"
                  @change="updateFormatValue(scope.row)"
                >
                  <el-option
                    v-for="field in typeOptions"
                    :key="field.dictValue"
                    :label="$t(field.dictLabel)"
                    :value="field.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('字段名称')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('字段名称') }}</span>
              <el-tooltip placement="top">
                <div slot="content">
                  <span
                    v-html="'sql的字段，如果没有写as就是字段本身，如果写了as就是字段的别名'"
                  />
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'fieldList.' + scope.$index + '.label'" :rules="fieldListRules.label">
                <el-input v-model="scope.row.label" :disabled="true" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('字段别名')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('字段别名') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'fieldList.' + scope.$index + '.fieldAlias'" :rules="fieldListRules.fieldAlias">
                <el-input v-model="scope.row.fieldAlias" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="form.imgType === 'BZT' ||form.imgType === 'ZZT' || form.imgType === 'ZXT'" :label="$t('分类')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('分类') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'fieldList.' + scope.$index + '.coordinates'" :rules="fieldListRules.coordinates">
                <el-select
                  v-model="scope.row.coordinates"
                  :placeholder="$t('请选择')"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="field in clearOptionList"
                    :key="field.dictValue"
                    :label="$t(field.dictLabel)"
                    :value="field.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('格式')" align="center">
            <template slot="header" slot-scope="{}">
              <span>{{ $t('格式') }}</span>
              <el-tooltip placement="top">
                <div slot="content">
                  <span
                    v-html="$t('年-月-日') + ': ' + 'yyyy-MM-dd' + '<br>' + $t('年-月-日 时-分-秒') + ': ' +
                      'yyyy-MM-dd HH:mm:ss' + '<br>' + $t('百分比') + ': ' + 'pct' + '<br>' +
                      $t('元') + ': ' + '###,###.##' + '<br>' + $t('万元') + ': ' + '###,###.####' + '<br>'"
                  />
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'fieldList.' + scope.$index + '.format'">
                <el-input v-model="scope.row.format" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('字段长度')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('字段长度') }}</span>
              <el-tooltip placement="top">
                <div slot="content">
                  <span
                    v-html="'文本：默认为255，过程创建临时表有可能出现内容超过定义的长度。<br>数字/日期：由后台赋值。'"
                  />
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'fieldList.' + scope.$index + '.fieldLength'" :rules="fieldListRules.fieldLength">
                <el-input v-model="scope.row.fieldLength" />
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column :label="$t('排序')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('排序') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'fieldList.' + scope.$index + '.sort'" :rules="fieldListRules.sort">
                <el-input v-model="scope.row.sort" />
              </el-form-item>
            </template>
          </el-table-column> -->
        </el-table>
        <!-- 参数列表 -->
        <div class="area-header mt-15">
          <span v-if="filedShow" class="area-header-title" style="float: left;">{{ $t('参数列表') }}</span>
        </div>
        <el-table
          v-if="filedShow"
          :data="form.paramsList"
          border
          class="nowrapTable formTable"
        >
          <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="60">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('参数类型')" align="center" min-width="100px">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('参数类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'paramsList.' + scope.$index + '.type'" :rules="paramsListRules.type">
                <el-select
                  v-model="scope.row.type"
                  clearable
                  :placeholder="$t('请选择')"
                  style="width: 100%"
                  @change="updateFormatValue(scope.row)"
                >
                  <el-option
                    v-for="field in typeParamOptions"
                    :key="field.dictValue"
                    :label="$t(field.dictLabel)"
                    :value="field.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('参数名称')" align="center" min-width="120px">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('参数名称') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'paramsList.' + scope.$index + '.label'" :rules="paramsListRules.label">
                <el-input v-model="scope.row.label" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('参数值')" align="center" min-width="140px">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('参数值') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'paramsList.' + scope.$index + '.value'" :rules="paramsListRules.value">
                <el-input v-model="scope.row.value" />
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column :label="$t('格式')" align="center">
            <template slot="header" slot-scope="{}">
              <span>{{ $t('格式') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.format" />
              </el-form-item>
            </template>
          </el-table-column> -->
          <el-table-column :label="$t('排序')" align="center" min-width="90px">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('排序') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'paramsList.' + scope.$index + '.sort'" :rules="paramsListRules.sort">
                <el-input v-model="scope.row.sort" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('指标')" align="center" min-width="150px">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('指标') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item v-if="scope.row.type === 'ZB'" :prop="'paramsList.' + scope.$index + '.keyId'" :rules="paramsListRules.keyId">
                <el-select
                  v-model="scope.row.keyId"
                  clearable
                  :placeholder="$t('请选择')"
                  style="width: 100%"
                  @change="updateKeyId(scope.row)"
                >
                  <el-option
                    v-for="keys in paramsKeyList"
                    :key="keys.id"
                    :label="$t(keys.label)"
                    :value="keys.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('实际值')" align="center" min-width="140px">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('实际值') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item v-if="scope.row.type === 'ZB'" :prop="'paramsList.' + scope.$index + '.keyValue'" :rules="paramsListRules.keyValue">
                <el-select
                  v-model="scope.row.keyValue"
                  clearable
                  :placeholder="$t('请选择')"
                  style="width: 100%"
                >
                  <el-option
                    v-for="columns in getColumnListByParentId(scope.row.keyId)"
                    :key="columns.id"
                    :label="$t(columns.fieldAlias)"
                    :value="columns.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('展示值')" align="center" min-width="140px">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('展示值') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item v-if="scope.row.type === 'ZB'" :prop="'paramsList.' + scope.$index + '.keyLabel'" :rules="paramsListRules.keyLabel">
                <el-select
                  v-model="scope.row.keyLabel"
                  clearable
                  :placeholder="$t('请选择')"
                  style="width: 100%"
                >
                  <el-option
                    v-for="columns in getColumnListByParentId(scope.row.keyId)"
                    :key="columns.id"
                    :label="$t(columns.fieldAlias)"
                    :value="columns.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="!isBuiltin" :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="80">
            <template slot-scope="scope">
              <el-button
                size="small"
                type="text"
                icon="el-icon-delete"
                @click="deleteHandle(scope.$index)"
              >{{ $t('删除') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- <div v-if="filedShow && !isBuiltin" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPayment">{{ $t("添加") }}</el-button>
        </div> -->
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;margin-top: 60px;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <save-btn has-permi="system:word" />
    </div>
    <!--预览数据-->
    <el-dialog :title="$t('预览数据')" :visible.sync="previewOpen" width="80%" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <el-form ref="form" v-loading="dataLoading" :model="form" :rules="paramsRules" class="dataForm" @submit.native.prevent>
        <!-- 动态参数  -->
        <div class="area-header mt-15">
          <span v-if="filedShow" class="area-header-title">{{ $t('查询参数') }}</span>
        </div>
        <div v-if="mapObject && mapObject !== null && mapObject.length > 0" style="margin-top:10px">
          <el-form-item v-for="(item,index) in mapObject" :key="index" :rules="[{ required: true, message: $t('必填字段') }]">
            <div v-if="item.isShow === 'true'">
              <span slot="label">
                <span style="color: red; font-size: 16px;">*</span>
                <span>{{ $t(item.label) }}</span>
                <!-- <span v-if="defaultFormat.includes(item.format)">{{ item.templateLabel }}</span> -->
              <!--            <el-tooltip v-if="!defaultFormat.includes(item.format)" :content="item.sql" placement="top">-->
              <!--              <i class="el-icon-question" />-->
              <!--            </el-tooltip>-->
              </span>
              <div><el-input v-if="item.type === 'WB'" v-model="item.param" style="width: 100%" :placeholder="$t('请输入')" /></div>
              <div><Money v-if="item.type === 'JE'" v-model="item.param" style="width: 100%" :placeholder="$t('请输入')" /></div>
              <div><DatePicker v-if="item.type === 'RQ'" v-model="item.param" style="width: 100%" type="date" :placeholder="$t('请选择')" /></div>
              <div><UserSelect v-if="item.type === 'RY'" v-model="item.param" style="width: 100%" :placeholder="$t('请选择')" /></div>
              <div>
                <el-select
                  v-if="item.type === 'ZB'"
                  v-model="item.param"
                  clearable
                  :placeholder="$t('请选择')"
                  style="width: 100%"
                >
                  <el-option
                    v-for="result in queryResultObject[item.id]"
                    :key="result.value"
                    :label="$t(result.label)"
                    :value="result.value"
                  />
                </el-select>
              </div>
              <!-- <div v-if="defaultFormat.includes(item.format)" :class="'mainBody' + index">
                <MainBodySelect
                  :key="new Date().getTime()"
                  v-model="item.param"
                  :parameters="item.format"
                  :width="'100%'"
                  :show-label="false"
                  @change="repeatAutoFill(item.param, item.format)"
                />
              </div> -->
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t('查询') }}</el-button>
          </el-form-item>
        </div>
      </el-form>
      <el-table v-loading="tableDataLoading" :data="previewData" style="width: 100%">
        <el-table-column v-for="(item, index) in tableColumns" :key="index" :prop="item.fieldName" min-width="200px" :label="item.title" :show-overflow-tooltip="true" tooltip-effect="darkTable" class="nowrapTable" />
      </el-table>
    </el-dialog>
    <el-dialog :title="$t(quoteTitle)" :visible.sync="quoteOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="" width="80%" append-to-body>
      <wordOnlineKeyWordQuoteList ref="wordOnlineKeyWordQuoteList" />
    </el-dialog>
    <el-dialog :title="$t('引用物理表情况')" :visible.sync="quoteTableOpen" width="20%" :close-on-click-modal="false" :lock-scroll="false" custom-class="" append-to-body>
      <wordOnlineKeyQuoteTableForm ref="wordOnlineKeyQuoteTableForm" />
    </el-dialog>
  </div>
</template>

<script>
import { saveWordOnlineKeyWord, getWordOnlineKeyWord,
  listWordOnlineKeyWord, checkCodeRepeat, checkCodeFlagRepeat, checkKeywordLabel, getColumnOfKeyList,
  getResultByParamId } from '@/api/system/word/keyword/wordOnlineKeyWord'
import { getColumnBySql, previewSqlResult } from '@/api/system/search/searchSqlBase'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { optionselect as getDictOptionselect } from '@/api/system/dict/type'
import wordOnlineKeyWordQuoteList from './wordOnlineKeyWordQuoteList.vue'
import { getAllDataSource } from '@/api/system/word/wordOnlineKeyDataSource'
import wordOnlineKeyQuoteTableForm from '../../wordOnlineKeyQuoteTableForm.vue'

import 'codemirror/theme/ambiance.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/addon/hint/show-hint.css'
import { codemirror } from 'vue-codemirror'

require('codemirror/addon/edit/matchbrackets')
require('codemirror/addon/selection/active-line')
require('codemirror/mode/sql/sql')
require('codemirror/addon/hint/show-hint')
require('codemirror/addon/hint/sql-hint')
require('codemirror/addon/display/autorefresh')

export default {
  components: {
    Treeselect,
    wordOnlineKeyWordQuoteList,
    codemirror,
    wordOnlineKeyQuoteTableForm
  },
  data() {
    var checkCodeRepeatMethod = (rule, value, callback) => {
      // 先查看是否符合规则
      const regex = /^[a-zA-Z0-9_]+$/
      if (this.form.type !== 'folder' && !regex.test(value)) {
        this.codeDisabled = false
        callback('输入只能包含大小写字母、数字和下划线')
      }
      checkCodeRepeat(this.form.code).then((response) => {
        if (!this.form.id) {
          if (!value) {
            return callback(new Error(this.$t('必填信息!')))
          }
          if (response.data !== null && response.data.length > 0) {
            callback(new Error(this.$t('标识已存在!')))
          } else {
            callback()
          }
        } else {
          if (response.data !== null && response.data.length > 0) {
            var count = 0
            response.data.forEach(item => {
              if (item.id !== this.form.id && item.code === value) {
                count++
              }
            })
            if (count > 0) {
              callback(new Error(this.$t('标识已存在!')))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
      })
    }
    var checkCodeFlagRepeatMethod = (rule, value, callback) => {
      // 先查看是否符合规则
      const regex = /^[a-zA-Z0-9_]+$/
      if (this.form.type !== 'folder' && !regex.test(value)) {
        this.codeFlagDisabled = false
        callback('输入只能包含大小写字母、数字和下划线')
      }
      checkCodeFlagRepeat(this.form.codeFlag).then((response) => {
        if (!this.form.id) {
          if (!value) {
            return callback(new Error(this.$t('必填信息!')))
          }
          if (response.data !== null && response.data.length > 0) {
            callback(new Error(this.$t('标识已存在!')))
          } else {
            callback()
          }
        } else {
          if (response.data !== null && response.data.length > 0) {
            var count = 0
            response.data.forEach(item => {
              if (item.id !== this.form.id && item.code === value) {
                count++
              }
            })
            if (count > 0) {
              callback(new Error(this.$t('标识已存在!')))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
      })
    }
    const checkOptionList = (rule, value, callback) => {
      if (this.form.fieldList) {
        var temp = []
        this.form.fieldList.forEach((item) => {
          if (
            item.coordinates !== null &&
            item.coordinates !== undefined &&
            item.coordinates !== ''
          ) {
            temp.push(item.coordinates)
          }
        })
        var flag = true
        const filteredArray = temp.filter(item => item === 'X_ROW')
        if (filteredArray.length > 1) {
          flag = false
          callback(new Error(this.$t('只能有一个X轴行')))
        }
        const filteredColArray = temp.filter(item => item === 'X_COL')
        if (filteredColArray.length === 0) {
          flag = false
          callback(new Error(this.$t('请选择至少1个元素')))
        }
        // 如果是饼状图只能选择一个元素
        if (this.form.imgType === 'BZT') {
          if (filteredColArray.length > 1) {
            flag = false
            callback(new Error(this.$t('饼状图只可以选择一个元素')))
          }
        }

        if (flag) {
          callback()
        }
       /** if (value === undefined || value === '' || value === null) {
          callback(new Error(this.$t('必填信息')))
        } else {
          var count = 0
          temp.forEach((item) => {
            if (item === value) {
              count++
            }
          })
          if (count > 1) {
            callback(new Error(this.$t('不能重复选择')))
          } else {
            callback()
          }
        } **/
      } else {
        callback()
      }
    }
    // 校验名称是否重复
    const keywordLabel = (rule, value, callback) => {
      checkKeywordLabel(this.form.keyWord).then((response) => {
        if (this.form.type === 'folder' && !this.form.id) {
          if (!value) {
            return callback(new Error(this.$t('必填信息!')))
          }
          if (response.data === null) {
            callback(new Error(this.$t('异常,未获取到标识')))
          } else if (response.data.length > 0) {
            callback(new Error(this.$t('名称已存在!')))
          } else {
            callback()
          }
        } else {
          callback()
        }
      })
    }
    // 校验字段列表中是否包含中文
    const whetherToIncludeChinese = (rule, value, callback) => {
      if (value === undefined || value === '' || value === null) {
        callback(new Error(this.$t('必填信息')))
      } else {
        callback()
      }
    }
    return {
      // 表单参数
      form: {},
      // 遮罩层
      loading: false,
      editor: {},
      previewOpen: false,
      previewData: [],
      tableColumns: [],
      codeDisabled: true,
      codeFlagDisabled: true,
      // 表单校验
      rules: {
        keyWord: [{ required: true, validator: keywordLabel, trigger: ['blur', 'change'] }],
        busType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        textType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        type: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        code: [{ required: true, validator: checkCodeRepeatMethod, trigger: ['blur', 'change'] }],
        codeFlag: [{ required: true, validator: checkCodeFlagRepeatMethod, trigger: ['blur', 'change'] }],
        // singleMultiple: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        imgType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        parentId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        isBuiltinData: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        usageScope: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        sqlScript: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        dataSourceId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      fieldListRules: {
        label: [
          { required: true, validator: whetherToIncludeChinese, trigger: ['blur', 'change'] }
        ],
        fieldAlias: [
          { required: true, message: this.$t('必填信息'), trigger: 'change' }
        ],
        type: [
          { required: true, message: this.$t('必填信息'), trigger: 'change' }
        ],
        coordinates: [
          { required: true, validator: checkOptionList, trigger: 'change' }
        ],
        sort: [
          { required: true, message: this.$t('必填信息'), trigger: 'change' }
        ],
        fieldLength: [
          { required: true, message: this.$t('必填信息'), trigger: 'change' }
        ]
      },
      paramsListRules: {
        label: [
          { required: true, message: this.$t('必填信息'), trigger: 'change' }
        ],
        value: [
          { required: true, message: this.$t('必填信息'), trigger: 'change' }
        ],
        type: [
          { required: true, message: this.$t('必填信息'), trigger: 'change' }
        ],
        sort: [
          { required: true, message: this.$t('必填信息'), trigger: 'change' }
        ],
        keyId: [
          { required: true, message: this.$t('必填信息'), trigger: 'change' }
        ],
        keyValue: [
          { required: true, message: this.$t('必填信息'), trigger: 'change' }
        ],
        keyLabel: [
          { required: true, message: this.$t('必填信息'), trigger: 'change' }
        ]
      },
      typeOptions: [],
      typeParamOptions: [],
      searchSqlBack: '',
      keyWordOptions: [],
      typeFolderOrKeyWOrdOptions: [],
      singleMultipleOptions: [],
      chartTypeOptions: [],
      dictOptions: [],
      // 字典列表是否显示
      filedShow: true,
      isHidden: false,
      numberOfInspections: 0,
      clearOptionList: [
        { dictLabel: 'X轴行', dictValue: 'X_ROW' },
        { dictLabel: '元素', dictValue: 'X_COL' }
        // { dictLabel: 'Y轴', dictValue: 'Y' }
      ],
      numberOption: [],
      // 记录sql提交时用预校验是否有过更改,更改过的话需要重新测试保证sql有效性
      oldSqlScript: '',
      backFiledList: [],
      /**
       * 预览数据的参数
       */
      dataLoading: false,
      quoteTableOpen: false,
      tableDataLoading: false,
      paramsRules: {},
      mapObject: undefined,
      paramsKeyList: [],
      paramsColumnList: [],
      queryResultObject: {},
      keyWordList: ['single', 'multivalued', 'image'],
      isBuiltinData: 'N',
      quoteTitle: '引用情况',
      quoteOpen: false,
      cmOptions: {
        autorefresh: true,
        tabSize: 2,
        mode: 'text/x-mariadb',
        // theme: 'ambiance',
        indentWithTabs: true,
        smartIndent: true,
        lineNumbers: true,
        matchBrackets: true,
        readOnly: this.isBuiltin,
        extraKeys: { Ctrl: 'autocomplete' }, // 自定义快捷键
        hintOptions: { // 自定义提示选项
          tables: {
            users: ['name', 'score', 'birthDate'],
            countries: ['name', 'population', 'size']
          }
        }
      },
      builtInParams: ['${dataScope}'],
      templateTypeOptions: [{
          value: 'obj',
          label: '对象'
        }],
      dataSourceOptions: []
    }
  },
  computed: {
    isBuiltin() {
      // 是否内置的数据
      return this.form.id && this.isBuiltinData === 'Y'
    }
  },
  watch: {
    'form.type': {
      handler(type) {
        if (type === 'folder') {
          this.isHidden = false
        } else {
          this.isHidden = true
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.codeDisabled = true
    this.codeFlagDisabled = true
    this.$bus.$emit('async_quote')
    // 文本类型
    this.getDicts('single_multiple_type').then((response) => {
      this.singleMultipleOptions = response.data
    })
    // 类型
    this.getDicts('key_word_directory_text').then((response) => {
      this.typeFolderOrKeyWOrdOptions = response.data
    })
    // 字段类型
    this.getDicts('key_word_field_type').then((response) => {
      this.typeOptions = response.data
    })
    // 字段类型
    this.getDicts('key_word_param_type').then((response) => {
      this.typeParamOptions = response.data
    })
    // 图表类型
    this.getDicts('key_word_image_type').then((response) => {
      this.chartTypeOptions = response.data
    })
    /** 查询字典下拉列表 */
    getDictOptionselect().then((response) => {
      this.dictOptions = response.data
    })
    // 查询所有视图指标
    this.getKeyParamsList()
    // 获取是否内置数据的变量
    this.getIsBuiltinDataVariable()
    // 查询数据源
    this.getDataSource()
  },
  mounted() {
  },
  methods: {
    // 初始化数据
    init(data) {
      // 上级目录
      this.numberOfInspections = 0
      // 默认选中目录
      this.form.type = 'folder'
      this.getParentFolderSelect()
      this.filedShow = false
      this.loading = false
      if (data != null && data.id !== undefined) {
        this.loading = true
        getWordOnlineKeyWord(data.id).then((response) => {
          this.form = response.data
          this.oldSqlScript = this.form.sqlScript
          if (this.form.type === 'key_word' || this.form.type === 'key_word_tree' || this.keyWordList.includes(this.form.type)) {
            if (this.form.fieldList === undefined || this.form.fieldList <= 0) {
              // this.checkScriptBySql()
            } else {
              this.numberOfInspections++
            }
            this.filedShow = true
          }
          this.backFiledList = this.form.fieldList
          this.loading = false
        })
      } else {
        this.numberOfInspections++
        this.reset()
      }
    },
    // 去掉children=[]的children属性 respectively
    normalizer(node) {
      if ((node.children && !node.children.length) || node.children === null) {
        delete node.children
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        code: undefined,
        parentId: '0',
        type: 'folder',
        keyWord: undefined,
        busType: undefined,
        textType: undefined,
        singleMultiple: undefined,
        sqlScript: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        dataSourceId: '1'
      }
      this.$refs.sqlScript.codemirror.setValue('')
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      this.$parent.$parent.formOpen = false
      // 刷新list页面
      if (!(this.$parent.$parent.flag && this.$parent.$parent.flag === 'quote')) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm: async function() {
      this.form.sqlScript = (this.$refs.sqlScript && this.$refs.sqlScript.codemirror) ? this.$refs.sqlScript.codemirror.getValue() : ''
      var submitFlag = true
      if (this.isHidden) {
        if (this.oldSqlScript !== '' && this.oldSqlScript !== this.form.sqlScript) {
          this.msgError(this.$t('请先测试sql合法性'))
          submitFlag = false
        }
      }
      // 校验一级 主目类是否是关键字
      if ((this.form.parentId === '0' || this.form.parentId === 0) && this.keyWordList.includes(this.form.type)) {
        this.msgError(this.$t('主类目不能添加关键字'))
        submitFlag = false
      }
      this.$refs['form'].validate((valid) => {
        if (valid && submitFlag) {
          this.loading = true
          saveWordOnlineKeyWord(this.form).then((response) => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.closeForm()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    checkScriptBySql: async function() {
      if (this.form.dataSourceId !== '1' && this.form.dataType !== 'table') {
        this.msgError(this.$t('选择了外部数据源只能选择物理表'))
        return
      }
      this.form.searchSql = this.$refs.sqlScript.codemirror.getValue()
      this.searchSqlBack = this.form.searchSql
      // 把里面所有的数字全部显示出来
      var sqlArray = this.form.searchSql.match(/[^{]+(?=})/g)
      if (sqlArray) {
        sqlArray.forEach((item) => {
          this.form.searchSql = this.form.searchSql.replace('${' + item + '}', '"1"')
        })
      }
      if (this.form.searchSql === null || this.form.searchSql === '') {
        this.$message.error('sql脚本不能为空')
      } else {
        this.oldSqlScript = this.searchSqlBack
        // 如果是过程不替换参数 去后台替换
        if (this.form.dataType === 'proc') {
          this.form.searchSql = this.searchSqlBack
        }
        await getColumnBySql(this.form).then((response) => {
          this.form.searchSql = this.searchSqlBack
          var aliasMap = {}
          if (response.datas && response.datas.aliasMap) {
            aliasMap = response.datas.aliasMap
          }
          if (response.data) {
            // if (this.form.type === 'image') {
            //   if (this.form.imgType === 'BZT') {
            //     if (response.data.length !== 2) {
            //       this.msgError('关键字为饼状图时,sql必须取为两个字段!')
            //       this.form.fieldList = []
            //     }
            //   } else if (this.form.imgType === 'ZZT' || this.form.imgType === 'ZXT') {
            //     if (response.data.length !== 3) {
            //       this.msgError('关键字为柱状图/折线图时,sql必须取为三个字段!')
            //       this.form.fieldList = []
            //     }
            //   }
            // }
            // 保存之前配置的数据
            if (this.numberOfInspections > 0) {
              this.msgSuccess(this.$t('测试sql完成'))
            }
            this.numberOfInspections++
            var fieldList = []
            var newObject = {}
            if (this.form.fieldList && this.form.fieldList.length > 0) {
              newObject = this.form.fieldList.reduce((acc, curr) => {
                acc[curr.label] = curr
                return acc
              }, {})
            }

            for (var i = 0; i < response.data.length; i++) {
              if (!newObject[response.data[i].alias]) {
                var field = {}
                field.code = response.data[i].alias
                field.label = response.data[i].alias
                // 如果有存在别名 则使用别名
                if (aliasMap[response.data[i].alias]) {
                    field.fieldAlias = aliasMap[response.data[i].alias].fieldAlias ? aliasMap[response.data[i].alias].fieldAlias : response.data[i].alias
                    field.type = aliasMap[response.data[i].alias].fieldType ? aliasMap[response.data[i].alias].fieldType : 'WB'
                    field.fieldLength = aliasMap[response.data[i].alias].fieldLength ? aliasMap[response.data[i].alias].fieldLength : '255'
                    field.format = aliasMap[response.data[i].alias].format ? aliasMap[response.data[i].alias].format : ''
                } else {
                  field.fieldAlias = response.data[i].alias
                  field.type = 'WB'
                  field.fieldLength = '255'
                }

                field.fieldName = response.data[i].field
                field.coordinates = response.data[i].coordinates
                field.isShow = 'Y'
                field.sort = (i + 1) * 10
                fieldList.push(field)
                this.filedShow = true
              } else {
                // 说明已经存在了
                var existField = newObject[response.data[i].alias]
                existField.sort = (i + 1) * 10
                fieldList.push(existField)
                this.filedShow = true
              }
            }
            fieldList.sort((a, b) => a.sort - b.sort)
            this.$set(this.form, 'fieldList', fieldList)
            // 把识别到的关键字自动补充到下面
            // 先筛选存在的参数
            const regex = /\$\{([^}]+)\}/g
            // 使用match方法获取所有匹配的子字符串
            const matches = this.form.searchSql.match(regex)
            console.log('matches', matches)
            if (matches && matches.length > 0) {
              const filteredArray = (this.form.paramsList && this.form.paramsList.length > 0) ? this.form.paramsList.filter(obj => matches.includes(obj.value)) : []
              matches.forEach((item) => {
                // 排除内置函数
                if (!this.builtInParams.includes(item)) {
                  // 如果参数列表已经存在则不再增加
                  const existsInValue = filteredArray.some((obj) => obj.value === (item))
                  if (!existsInValue) {
                    const row = {
                      value: item,
                      sort: (filteredArray.length + 1) * 10
                    }
                    if (aliasMap[item]) {
                      row.label = aliasMap[item].fieldAlias
                      row.type = aliasMap[item].fieldType ? aliasMap[item].fieldType : 'WB'
                    }
                    filteredArray.push(row)
                  }
                }
              })
              this.$set(this.form, 'paramsList', filteredArray)
            }
            // 如果当前类型是 如果是一个字段就是文本 大于一个字段是列表
            if (response.data.length === 1) {
              if (this.form.type !== 'single') {
                this.$confirm('识别到「1」个字段，是否要切换到文本类型?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  this.$set(this.form, 'type', 'single')
                  this.$message({
                    type: 'success',
                    message: '修改成功!'
                  })
                }).catch(() => {
                })
              }
            } else {
              if (this.form.type === 'single') {
                this.$set(this.form, 'type', 'multivalued')
              }
            }
          } else {
            this.msgError(this.$t('sql脚本异常!'))
          }
        })
      }
    },
    previewScriptBySql: async function() {
      this.form.sqlScript = this.$refs.sqlScript.codemirror.getValue()
      if (this.isHidden) {
        if (this.oldSqlScript !== '' && this.oldSqlScript !== this.form.sqlScript) {
          this.msgError(this.$t('请先测试sql合法性'))
          return
        }
      }
      this.form.searchSql = this.$refs.sqlScript.codemirror.getValue()
      this.searchSqlBack = this.form.searchSql
      // 把里面所有的数字全部显示出来
      var sqlArray = this.form.searchSql.match(/[^{]+(?=})/g)
      // if (sqlArray) {
      //   sqlArray.forEach((item) => {
      //     this.form.searchSql = this.form.searchSql.replace('${' + item + '}', '"1"')
      //   })
      // }
      if (this.form.searchSql === null || this.form.searchSql === '') {
        this.$message.error('sql脚本不能为空')
      } else if (sqlArray && sqlArray.length > 0) {
          var openflag = true
            // 查看是否有参数 有的话展示参数
          this.mapObject = this.form.paramsList
          if (this.mapObject) {
            // var tempKeyWord = []
            // 目的是让每种类型的输入框只展示一个.
            for (const item of this.mapObject) {
              if (!item.type) {
                this.msgError(this.$t('请先维护参数列表'))
                openflag = false
              }
              // 如果是指标 先去查询下拉选项
              if (item.type === 'ZB') {
                await this.getQueryResult(item.id)
              }
              // if (!tempKeyWord.includes(item.templateLabel)) {
              //   tempKeyWord.push(item.templateLabel)
                item.isShow = 'true'
              // } else {
              //   item.isShow = 'false'
              // }
            }
          }
          if (openflag) {
            // 如果sql有参数则不查询 直接打开预览界面先选择参数
            this.previewOpen = true
            this.tableColumns = []
          }
      } else {
        // this.oldSqlScript = this.searchSqlBack
        this.tableDataLoading = true
        await previewSqlResult(this.form).then((response) => {
          this.form.searchSql = this.searchSqlBack
          if (response.data) {
            this.previewData = response.data
              // 根据返回的数据动态生成表格列配置项
            if (this.previewData.length > 0) {
              this.previewOpen = true
              this.tableColumns = []
              Object.keys(this.previewData[0]).forEach((key) => {
                this.tableColumns.push({ fieldName: key, title: key })
              })
              this.$forceUpdate()
            } else {
              this.msgWarning(this.$t('未查询出数据!'))
            }
            this.tableDataLoading = false
          } else {
            this.msgError(this.$t('sql脚本异常!'))
          }
        })
      }
    },
    async queryHandle() {
      var flag = false
      var param = ''
      this.mapObject.forEach(item => {
        if (!item.param) {
          flag = true
        }
        param += item.value + '@' + item.param + '*'
      })
      if (flag) {
        this.msgError(this.$t('请输入必填项'))
      } else {
        this.tableDataLoading = true
        this.form.paramStr = param
        await previewSqlResult(this.form).then((response) => {
          this.form.searchSql = this.searchSqlBack
          if (response.data) {
            this.previewData = response.data
              // 根据返回的数据动态生成表格列配置项
            if (this.previewData.length > 0) {
              this.previewOpen = true
              this.tableColumns = []
              Object.keys(this.previewData[0]).forEach((key) => {
                this.tableColumns.push({ fieldName: key, title: key })
              })
              this.$forceUpdate()
            } else {
              this.msgWarning(this.$t('未查询出数据!'))
            }
            this.tableDataLoading = false
          } else {
            this.msgError(this.$t('sql脚本异常!'))
          }
        })
      }
    },
    // 检查是否可选
    checkIfItIsOptional() {
      this.keyWordOptions.forEach((item) => {
        item.isDisabled = (item.type !== 'folder')
        this.checkIfItIsOptionalSub(item)
      })
    },
    checkIfItIsOptionalSub(data) {
      if (data !== null && data.children !== null) {
        data.children.forEach((item) => {
          item.isDisabled = (item.type !== 'folder')
          this.checkIfItIsOptionalSub(item)
        })
      }
    },
    // 设置格式化字段默认值
    updateFormatValue: function(row) {
      if (row.type === 'JE') {
        row.format = '###,###.##'
      } else if (row.type === 'RQ') {
        row.format = 'yyyy-MM-dd'
      } else {
        row.format = ''
      }
    },
    getParentFolderSelect() {
      listWordOnlineKeyWord({}).then((response) => {
        this.keyWordOptions = []
        const menu = {
          id: 0,
          label: this.$t('主类目'),
          children: [],
          type: 'folder'
        }
        if (response.data) {
          menu.children = response.data
        }
        this.keyWordOptions.push(menu)
        this.checkIfItIsOptional()
      })
    },
    // 参数列表添加
    addPayment() {
      const len = this.form.paramsList ? this.form.paramsList.length : 0
      const row = {
        id: undefined,
        label: undefined,
        type: undefined,
        format: undefined,
        sort: (len + 1) * 10
      }
      if (!(this.form.paramsList instanceof Array)) {
        this.$set(this.form, 'paramsList', [])
      }
      this.$nextTick(() => {
        this.form.paramsList.push(row)
      })
    },
    // 参数列表删除
    deleteHandle(index) {
      this.form.paramsList.splice(index, 1)
    },
    // 关键字树
    typeChangeToSingleMultiple(val) {
      if (val === 'key_word_tree') {
        this.form.singleMultiple = 'single'
      } else {
        this.form.singleMultiple = undefined
      }
    },
    getKeyParamsList() {
      getColumnOfKeyList().then((response) => {
        this.paramsKeyList = response.data
      })
    },
    getColumnListByParentId(keyId) {
      return this.paramsKeyList.find(list => list.id === keyId)?.fieldList || []
    },
    // eslint-disable-next-line no-unused-vars
    updateKeyId(row) {
    },
    async getQueryResult(id) {
      this.queryResultObject[id] = await this.getResultByParamInfo(id)
    },
    getResultByParamInfo(id) {
      // eslint-disable-next-line no-unused-vars
      return new Promise((resolve, reject) => {
        getResultByParamId(id).then((response) => {
          resolve(response.data.result)
        })
      })
    },
    getIsBuiltinDataVariable() {
      this.getConfigKey('is_builtin_data').then(res => {
        if (res.msg && res.msg === 'Y') {
          this.isBuiltinData = res.msg
        }
      })
    },
    /**
     * 查看引用/被引用情况
     */
    viewQuoteList(row, type) {
      if (type === 'quote') {
        this.quoteTitle = '引用情况'
      } else {
        this.quoteTitle = '被引用情况'
      }
      this.quoteOpen = true
      this.$nextTick(() => {
        // 调用form页面的 init 方法初始化数据
        this.$refs.wordOnlineKeyWordQuoteList.init(row, type)
      })
    },
    /**
     * 查看引用物理表情况
     */
     viewQuoteTableList(row) {
      this.quoteTableOpen = true
      this.$nextTick(() => {
        this.$refs.wordOnlineKeyQuoteTableForm.init(row)
      })
    },
    getDataSource() {
      getAllDataSource().then(response => {
        this.dataSourceOptions = response.data
        const defalutObj = {
          id: '1',
          dataSourceName: '默认当前数据源'
        }
        this.dataSourceOptions.unshift(defalutObj)
      })
    }
  }
}
</script>
<style scoped>
.codesql {
  font-size: 11pt;
  font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono,
    DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
}
</style>
